# import sys
# from PyQt6.QtWidgets import QApplication
# from PyQt6 import QtWidgets,QtCore,QtGui
# from PyQt6.QtGui import *
# from PyQt6.QtWidgets import *
# import time
# import PyQt6
# from faceInput import Ui_face_input
# from mainRec import QmyRec
# from user import *
# from PyQt6.QtWidgets import *


# class QmyFace(QWidget):
#     # 跳转信号
#     switch_window4 = QtCore.pyqtSignal()

#     def __init__(self,parent=None):
#         super().__init__(parent)
#         self.face_input = Ui_face_input()
#         self.face_input.setupUi(self)
#         self.setGeometry(700, 800, 700, 800)
#         self.center()
#         self.setWindowTitle('比奇堡在逃海绵')
#         self.timer_camera = QtCore.QTimer()
#         self.cap = cv2.VideoCapture()
#         self.CAM_NUM = 0
#         self.recc = QmyRec()
#         self.slot_face()
#         self.face_input.return_2.clicked.connect(self.go_face_main)

#     def go_face_main(self):
#         self.switch_window4.emit()

#     def paintEvent(self, event):
#         painter = QPainter(self)
#         pixmap = QPixmap("人脸录入.png")
#         # 绘制窗口背景，平铺到整个窗口，随着窗口改变而改变
#         painter.drawPixmap(self.rect(), pixmap)

#     def slot_face(self):
#         self.face_input.openCamera_3.clicked.connect(self.button_open_camera_click)
#         self.timer_camera.timeout.connect(self.show_camera)
#         self.face_input.clickCamera_3.clicked.connect(self.takePhoto)
#         self.face_input.closeCamera_3.clicked.connect(self.closeCamera)
#         self.face_input.save_3.clicked.connect(self.get_name1)
#         self.face_input.save_3.clicked.connect(self.save_pic)

#     '''保存按钮'''

#     def get_name1(self):  # 按钮"保存"被点击是获取文本框内容
#         name1 = self.face_input.name_3.text()
#         with open("output.txt", 'w', encoding='utf-8') as file:
#             file.write(name1)
#             file.close()
#         with open("users/all_people.txt", 'a', encoding='utf-8') as f:
#             f.write(name1 + ' ')
#             f.close()

#     '''打开摄像头'''

#     def button_open_camera_click(self):
#         if self.timer_camera.isActive() == False:
#             flag = self.cap.open(self.CAM_NUM)
#             if flag == False:
#                 msg = QtWidgets.QMessageBox.warning(
#                     PyQt6.QtWidgets.QApplication.activeWindow(), u"Warning", u"请检测相机与电脑是否连接正确",
#                     buttons=QtWidgets.QMessageBox.StandardButton.Ok,
#                     defaultButton=QtWidgets.QMessageBox.StandardButton.NoButton)
#             else:
#                 self.timer_camera.start(20)
#         else:
#             self.timer_camera.stop()  # 关闭定时器
#             self.cap.release()  # 释放视频流
#             self.face_input.pickCamera_3.clear()  # 清空视频显示区域

#     '''显示录入视频画面'''

#     def show_camera(self):
#         flag, self.image = self.cap.read()
#         # self.image = cv2.flip(self.image, 1)  # 左右翻转
#         # 特征提取
#         self.face_detect = FaceDetect()
#         self.face_detect.detect(self.image)
#         show = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)
#         # 视频流的长和宽
#         height, width = self.image.shape[:2]
#         showEnterImage = QtGui.QImage(show.data, width, height, QtGui.QImage.Format.Format_RGB888)
#         ratio = max(width / self.face_input.pickCamera_3.width(), height / self.face_input.pickCamera_3.height())
#         showEnterImage.setDevicePixelRatio(ratio)
#         # 视频流置于label中间部分播放
#         self.face_input.pickCamera_3.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
#         self.face_input.pickCamera_3.setPixmap(QtGui.QPixmap.fromImage(showEnterImage))
#         self.face_input.pickCamera_3.setScaledContents(True)
#         # return self.image

#     '''拍照并保存照片'''

#     def takePhoto(self):
#         if self.timer_camera.isActive() != False:
#             self.timer_camera.stop()
#             show = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)  # 左右翻转
#             # 视频流的长和宽
#             height, width = self.image.shape[:2]
#             showImage = QtGui.QImage(show.data, width, height, QtGui.QImage.Format.Format_RGB888)
#             ratio = max(width / self.face_input.pickCamera_3.width(), height / self.face_input.pickCamera_3.height())
#             showImage.setDevicePixelRatio(ratio)
#             # 视频流置于label中间部分播放
#             self.face_input.pickCamera_3.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
#             self.face_input.pickCamera_3.setPixmap(QtGui.QPixmap.fromImage(showImage))
#             self.face_input.pickCamera_3.setScaledContents(True)
#             self.take_img = showImage
#     '''保存名单'''

#     def save_pic(self):
#         with open("output.txt", 'r') as file:
#             name = file.readline()
#             file.close()
#         # print(name)
#         # time.sleep(3)
#         image = self.image
#         Register(name, image)
#         # print(image)
#         # cv2.putText(image, '',
#         #             (int(image.shape[1] / 2 - 130), int(image.shape[0] / 2)),
#         #             cv2.FONT_HERSHEY_SCRIPT_COMPLEX,
#         #             1.0, (255, 0, 0), 1)
#         self.timer_camera.start()

#     '''关闭录入摄像头'''

#     def closeCamera(self):

#         # self.face_input.openCamera_3.setEnabled(True)
#         # self.face_input.closeCamera_3.setEnabled(False)
#         self.timer_camera.stop()
#         self.cap.release()
#         self.face_input.pickCamera_3.clear()

#     '''屏幕居中'''
#     def center(self):
#         qr = self.frameGeometry()  # 得到一个指定主窗口几何形状的矩形
#         cp = self.screen().availableGeometry().center()  # 计算出显示器的分辨率，通过分辨率得出中心点
#         qr.moveCenter(cp)  # 设置为屏幕的中心，矩形大小不变
#         self.move(qr.topLeft())


# if __name__ == '__main__':
#     app = QApplication(sys.argv)
#     app.setWindowIcon(QIcon('logo.ico'))
#     myWidget = QmyFace()
#     myWidget.show()
#     sys.exit(app.exec())



import sys
import cv2
import numpy as np
from PyQt6 import QtWidgets, QtCore, QtGui
from PyQt6.QtGui import QPainter, QPixmap
from PyQt6.QtWidgets import QApplication, QWidget, QMessageBox
from faceInput import Ui_face_input
from mainRec import QmyRec
from user import Register
from face_detect import FaceDetect  # 假设你有人脸检测模块

# 视频处理线程类
class VideoThread(QtCore.QThread):
    # 信号用于将处理后的视频帧发送到主界面显示
    change_pixmap_signal = QtCore.pyqtSignal(np.ndarray)

    def __init__(self, cam_num, face_detect):
        super().__init__()
        self.cap = cv2.VideoCapture(cam_num)
        self.running = True
        self.face_detect = face_detect  # 实例化传入的人脸检测模块

    def run(self):
        while self.running:
            ret, frame = self.cap.read()
            if ret:
                # 人脸检测或其他处理
                self.face_detect.detect(frame)
                # 发出信号传递处理后的帧
                self.change_pixmap_signal.emit(frame)

    def stop(self):
        self.running = False
        self.cap.release()

# 主窗口类
class QmyFace(QWidget):
    switch_window4 = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.face_input = Ui_face_input()
        self.face_input.setupUi(self)
        self.setGeometry(700, 800, 700, 800)
        self.center()
        self.setWindowTitle('比奇堡在逃海绵')
        self.recc = QmyRec()
        self.slot_face()

        # 初始化人脸检测模块和视频线程
        self.face_detect = FaceDetect()  # 假设你有此类实现
        self.video_thread = None  # 视频线程

        self.face_input.return_2.clicked.connect(self.go_face_main)

    def go_face_main(self):
        self.switch_window4.emit()

    def paintEvent(self, event):
        painter = QPainter(self)
        pixmap = QPixmap("人脸录入.png")
        painter.drawPixmap(self.rect(), pixmap)

    def slot_face(self):
        self.face_input.openCamera_3.clicked.connect(self.button_open_camera_click)
        self.face_input.clickCamera_3.clicked.connect(self.takePhoto)
        self.face_input.closeCamera_3.clicked.connect(self.closeCamera)
        self.face_input.save_3.clicked.connect(self.get_name1)
        self.face_input.save_3.clicked.connect(self.save_pic)

    '''保存按钮'''
    def get_name1(self):
        name1 = self.face_input.name_3.text()
        with open("output.txt", 'w', encoding='utf-8') as file:
            file.write(name1)
        with open("users/all_people.txt", 'a', encoding='utf-8') as f:
            f.write(name1 + ' ')

    '''打开摄像头'''
    def button_open_camera_click(self):
        if not self.video_thread:  # 如果线程未启动，则启动摄像头线程
            self.video_thread = VideoThread(0, self.face_detect)  # 传入摄像头编号和人脸检测模块
            self.video_thread.change_pixmap_signal.connect(self.update_image)
            self.video_thread.start()
        else:
            self.video_thread.stop()
            self.video_thread = None

    '''更新图像显示'''
    def update_image(self, frame):
        # 将当前帧保存到 self.image，以便后续保存使用
        self.image = frame
        
        # 将图像从 BGR 转换为 RGB 格式
        rgb_image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        h, w, ch = rgb_image.shape
        qt_image = QtGui.QImage(rgb_image.data, w, h, ch * w, QtGui.QImage.Format.Format_RGB888)
        
        # 更新 QLabel 显示内容
        self.face_input.pickCamera_3.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
        self.face_input.pickCamera_3.setPixmap(QtGui.QPixmap.fromImage(qt_image).scaled(
            self.face_input.pickCamera_3.width(),
            self.face_input.pickCamera_3.height(),
            QtCore.Qt.AspectRatioMode.KeepAspectRatio))

    '''拍照并保存照片'''
    def takePhoto(self):
        if self.video_thread:
            self.video_thread.stop()  # 停止视频流
            self.save_pic()  # 调用保存方法

    '''保存照片和名字'''
    def save_pic(self):
        with open("output.txt", 'r') as file:
            name = file.readline()
        
        if hasattr(self, 'image'):
            Register(name, self.image)  # 保存图像和名字
        else:
            print("No image to save!")  # 防止在未赋值 image 时出错


    '''关闭摄像头'''
    def closeCamera(self):
        if self.video_thread:
            self.video_thread.stop()
            self.video_thread = None
        self.face_input.pickCamera_3.clear()

    '''屏幕居中'''
    def center(self):
        qr = self.frameGeometry()
        cp = self.screen().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())


if __name__ == '__main__':
    app = QApplication(sys.argv)
    myWidget = QmyFace()
    myWidget.show()
    sys.exit(app.exec())




